package platformlog_logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAddLogLogic 新增部署日志
func NewAddLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogLogic {
	return &AddLogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddLogLogic) AddLog(req *types.AddLogRequest) (resp *types.AddLogResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var insertSQL string
	tableName := l.svcCtx.Config.SQLite.Tables.DeploymentLogs
	if flag {
		tableName = l.svcCtx.Config.Mysql.Tables.DeploymentLogs
	}

	insertSQL = fmt.Sprintf(`
		INSERT INTO %s (cluster_id, task_id, node_host, component, component_role, step_number, message, log_level, created_at)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON DUPLICATE KEY UPDATE 
			message=VALUES(message),
			log_level=VALUES(log_level),
			created_at=VALUES(created_at)
		`, tableName)

	err = l.svcCtx.Conn.TransactCtx(context.Background(), func(ctx context.Context, sess sqlx.Session) error {
		for _, log := range req.DeployLogs {
			_, err = sess.ExecCtx(ctx, insertSQL, log.ClusterID, log.TaskID, log.NodeHost, log.Component, log.ComponentRole, log.StepNumber, log.Message, log.LogLevel, log.CreatedTime)
			if err != nil {
				logx.Errorf("failed to execute insert: %v", err)
				return err
			}
		}
		return nil
	})

	if err != nil {
		logx.Errorf("failed to add logs: %v", err)
		return nil, err
	}

	return &types.AddLogResponse{
		Code:    200,
		Message: "部署日志写入完成"}, nil
}
